﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Spacer {
	//public delegate void TreeVisitor<T>( T nodeData );

	public class Tree<T> : IEnumerable<Tree<T>> {
		public Tree() {
			Data = default(T);
			Children = new LinkedList<Tree<T>>();
		}

		public Tree( T data ) {
			Data = data;
			Children = new LinkedList<Tree<T>>();
		}

		public Tree<T> AddChild( T data ) {
			Tree<T> node = new Tree<T>( data );
			Children.AddFirst( node );
			return node;
		}

		public void AddChildNode( Tree<T> node ) {
			Children.AddFirst( node );
		}

		public Tree<T> GetChild( int i ) {
			foreach(Tree<T> n in Children)
				if( --i == 0 ) return n;
			return null;
		}

		public List<Tree<T>> ClearChildren() {
			List<Tree<T>> list = Children.ToList();
			Children.Clear();
			return list;
		}

		/*public void Traverse( Tree<T> node, TreeVisitor<T> visitor ) {
			visitor( node.Data );
			foreach(Tree<T> kid in node.Children)
				Traverse( kid, visitor );
		}*/

		public IEnumerator<Tree<T>> GetEnumerator() {
			return Children.GetEnumerator();
		}

		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
			return Children.GetEnumerator();
		}

		// ----------

		public T Data { get; set; }
		public LinkedList< Tree<T> > Children { get; set; }
	}
}
